#region Using Statements
using System;
using System.Xml.Linq;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
#endregion

namespace HOPE {
	/// <summary>
	/// This screen implements the actual game logic. It is just a
	/// placeholder to get the idea across: you'll probably want to
	/// put some more interesting gameplay in here!
	/// </summary>
	class GameplayScreen : GameScreen {

		#region Fields

		ContentManager content;

		SpriteFont menufont;

		Texture2D testpage;
		Texture2D playerpanel;

		//Texture2D davinaaktif;
		//Texture2D latifupasif;

		Texture2D audriannaaktif;
        Texture2D audriannapasif;
		Texture2D zakhaevaktif;
        Texture2D zakhaevpasif;

        Texture2D controlstick;
        Texture2D controlstickBoundary;
        Texture2D jumpbutton;
        Texture2D actionbutton;

		#region posisi
		Vector2 controlstickpos = new Vector2(55, 369);
        Vector2 controlstickBoundarypos = new Vector2(34, 347);
        Vector2 jumpbuttonpos = new Vector2(690, 370);
        Vector2 actionbuttonpos = new Vector2(610, 380);

        Vector2 playerPosition = new Vector2(100, 100);
		//Vector2 enemyPosition = new Vector2(100, 100);

        Vector2 testpagepos = new Vector2(0, 0);
        Vector2 playerpanelpos = new Vector2(0, 0);

		//Vector2 davinaaktifpos = new Vector2(0, 0);
		//Vector2 davinapasifpos = new Vector2(0, 0);
		//Vector2 latifuaktifpos = new Vector2(0, 0);
		//Vector2 latifupasifpos = new Vector2(200, 0);
        Vector2 zakhaevaktifpos = new Vector2(0, 0);
        Vector2 zakhaevpasifpos = new Vector2(120, 0);
        Vector2 audriannaaktifpos = new Vector2(0, 0);
        Vector2 audriannapasifpos = new Vector2(200, 10);
		#endregion

		bool isActionButtonClicked;
        bool isJumpButtonClicked;

		bool isAudriannaAktif = false;
		bool isZakhaevAktif = true;

		Random random = new Random();

        #endregion

		#region Initialization


        /// <summary>
        /// Constructor.
        /// </summary>
        public GameplayScreen()
        {
            TransitionOnTime = TimeSpan.FromSeconds(1.5);
            TransitionOffTime = TimeSpan.FromSeconds(0.5);

            EnabledGestures = GestureType.Tap;
			

        }

		/// <summary>
		/// Load graphics content for the game.
		/// </summary>
		public override void LoadContent () {
			if (content == null)
				content = new ContentManager(ScreenManager.Game.Services, "Content");


			LoadAssets();

			// A real game would probably have more content than this sample, so
            // it would take longer to load. We simulate that by delaying for a
            // while, giving you a chance to admire the beautiful loading screen.
            Thread.Sleep(1000);

            // once the load has finished, we use ResetElapsedTime to tell the game's
            // timing mechanism that we have just finished a very long frame, and that
            // it should not try to catch up.
            ScreenManager.Game.ResetElapsedTime();

            base.LoadContent();
        }

		/// <summary>
        /// Unload graphics content used by the game.
        /// </summary>
        public override void UnloadContent()
        {
            content.Unload();
        }

        public void LoadAssets()
        {
            // Loads the animation dictionary from an xml file
            //animations = new Dictionary<string, Animation>();
            //LoadAnimationFromXML();

            // Loads all textures that are required
            LoadTextures();

            // Create all game components
			//CreateGameComponents();
        }

		#region private argument(load animation)
        //private void LoadAnimationFromXML()
        //{
        //    XDocument doc = XDocument.Load
        //        ("Content/Textures/AnimationDefinitions.xml");
        //    XName = XName.Get("Definition");
        //    var definitions = doc.Document.Descendants(name);

            //loop all definitons in the XML
        //    foreach (var animationDefinition in definitions)
        //    {
        //        // Get the name of the animation
        //        string animationAlias = animationDefinition.Attribute("Alias").Value;
        //        Texture2D texture =
        //            ScreenManager.Game.Content.Load<Texture2D>
        //            (animationDefinition.Attribute("SheetName").Value);

        //        // Get the frame size (width & height)
        //        Point frameSize = new Point();
        //        frameSize.X = int.Parse(
        //            animationDefinition.Attribute("FrameWidth").Value);
        //        frameSize.Y = int.Parse(
        //            animationDefinition.Attribute("FrameHeight").Value);

        //        // Get the frames sheet dimensions
        //        Point sheetSize = new Point();
        //        sheetSize.X = int.Parse(
        //            animationDefinition.Attribute("SheetColumns").Value);
        //        sheetSize.Y = int.Parse(
        //            animationDefinition.Attribute("SheetRows").Value);



        //        Animation animation = new Animation(texture, frameSize, sheetSize);

        //        // Checks for sub-animation definition
        //        if (animationDefinition.Element("SubDefinition") != null)
        //        {
        //            int startFrame = int.Parse(
        //                animationDefinition.Element("SubDefinition")
        //                .Attribute("StartFrame").Value);

        //            int endFrame = int.Parse
        //                (animationDefinition.Element("SubDefinition")
        //                .Attribute("EndFrame").Value);

        //            animation.SetSubAnimation(startFrame, endFrame);
        //        }

        //        if (animationDefinition.Attribute("Speed") != null)
        //        {
        //            animation.SetFrameInterval(
        //                TimeSpan.FromMilliseconds(
        //                double.Parse(animationDefinition.Attribute("Speed").Value)));
        //        }

        //        // If the definition has an offset defined - it should be  
        //        // rendered relative to some element/animation
        //        if (null != animationDefinition.Attribute("OffsetX") &&
        //            null != animationDefinition.Attribute("OffsetY"))
        //        {
        //            animation.Offset = new Vector2(int.Parse
        //                (animationDefinition.Attribute("OffsetX").Value),
        //                int.Parse(animationDefinition.Attribute("OffsetY").Value));
        //        }

        //        animations.Add(animationAlias, animation);
        //    }
        //}

		#endregion

		#region private argument(load textures)
        private void LoadTextures()
        {
            //load font
            menufont = content.Load<SpriteFont>("Textures/Interface/Fonts/menufont");

            //load background
            testpage = content.Load<Texture2D>("Textures/MenuScreen/pauseoverlay");

            //load inteface
            playerpanel = content.Load<Texture2D>("Textures/Interface/StatusBar/Panel/playerpanel");
            
            //char interface
			//davinaaktif = content.Load<Texture2D>("Textures/Interface/StatusBar/Player/Active/davinaaktif");
            //davinapasif = content.Load<Texture2D>("");
            //latifuaktif = content.Load<Texture2D>("");
			//latifupasif = content.Load<Texture2D>("Textures/Interface/StatusBar/Player/Passive/latifupasif");
			zakhaevaktif = content.Load<Texture2D>("Textures/Characters/Potrait/Active/zakhaevaktif");
			zakhaevpasif = content.Load<Texture2D>("Textures/Characters/Potrait/Passive/zakhaevpasif");
			audriannaaktif = content.Load<Texture2D>("Textures/Characters/Potrait/Active/audriannaaktif");
			audriannapasif = content.Load<Texture2D>("Textures/Characters/Potrait/Passive/audriannapasif");

            //load control
            controlstick = content.Load<Texture2D>("Textures/GamePlay/Control/controlstick");
            controlstickBoundary = content.Load<Texture2D>("Textures/Gameplay/Control/controlstickBoundary");
            jumpbutton = content.Load<Texture2D>("Textures/Gameplay/Control/jumpbutton");
            actionbutton = content.Load<Texture2D>("Textures/Gameplay/Control/actionbutton");
        }
		#endregion

		#region private argument(create game components)
		private void CreateGameComponents () {
			//level = new Level(ScreenManager.Game);
			//ScreenManager.Game.Components.Add(level);
		}
        #endregion

        #endregion
		#region Update and Draw


		/// <summary>
		/// Updates the state of the game. This method checks the GameScreen.IsActive
		/// property, so the game will stop updating when the pause menu is active,
		/// or if you tab away to a different application.
		/// </summary>
		public override void Update (GameTime gameTime, bool otherScreenHasFocus,
													   bool coveredByOtherScreen) {
			base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);

			//player up panel changer
			if (isAudriannaAktif == true) {
				audriannapasif = audriannaaktif;
				audriannapasifpos = audriannaaktifpos;
				isZakhaevAktif = false;
				zakhaevaktif = zakhaevpasif;
				zakhaevaktifpos = zakhaevpasifpos;
			}
			else {
				audriannaaktif = audriannapasif;
				audriannaaktifpos = audriannapasifpos;
				isZakhaevAktif = true;
				zakhaevpasif = zakhaevaktif;
				zakhaevpasifpos = zakhaevaktifpos;
			}

				//if (isZakhaevAktif == true) {
				//    isAudriannaAktif = false;
				//}
				

			if (IsActive) {
				// Apply some random jitter to make the enemy move around.
				const float randomization = 10;

				//enemyPosition.X += (float)(random.NextDouble() - 0.5) * randomization;
				//enemyPosition.Y += (float)(random.NextDouble() - 0.5) * randomization;

				// Apply a stabilizing force to stop the enemy moving off the screen.
				//Vector2 targetPosition = new Vector2(
				//    ScreenManager.GraphicsDevice.Viewport.Width / 2 - gameFont.MeasureString("Insert Gameplay Here").X / 2, 
				//    200);

				//enemyPosition = Vector2.Lerp(enemyPosition, targetPosition, 0.05f);

				// TODO: this game isn't very fun! You could probably improve
				// it by inserting something more interesting in this space :-)
			}
		}


		/// <summary>
		/// Lets the game respond to player input. Unlike the Update method,
		/// this will only be called when the gameplay screen is active.
		/// </summary>
		public override void HandleInput (InputState input) {
			if (input == null)
				throw new ArgumentNullException("input");

			// Look up inputs for the active player profile.
			int playerIndex = (int)ControllingPlayer.Value;

			KeyboardState keyboardState = input.CurrentKeyboardStates[playerIndex];
			GamePadState gamePadState = input.CurrentGamePadStates[playerIndex];

			// if the user pressed the back button, we return to the main menu
			PlayerIndex player;
			if (input.IsNewButtonPress(Buttons.Back, ControllingPlayer, out player)) {
				LoadingScreen.Load(ScreenManager, false, ControllingPlayer, new BackgroundScreen(), new MainMenuScreen());
			}
			else {
				// Otherwise move the player position.
				Vector2 movement = Vector2.Zero;

				if (keyboardState.IsKeyDown(Keys.Left))
					movement.X--;

				if (keyboardState.IsKeyDown(Keys.Right))
					movement.X++;

				if (keyboardState.IsKeyDown(Keys.Up))
					movement.Y--;

				if (keyboardState.IsKeyDown(Keys.Down))
					movement.Y++;

				Vector2 thumbstick = gamePadState.ThumbSticks.Left;

				movement.X += thumbstick.X;
				movement.Y -= thumbstick.Y;

				if (movement.Length() > 1)
					movement.Normalize();

				playerPosition += movement * 2;
			}
		}


		/// <summary>
		/// Draws the gameplay screen.
		/// </summary>
		public override void Draw (GameTime gameTime) {
			// This game has a blue background. Why? Because!
			ScreenManager.GraphicsDevice.Clear(ClearOptions.Target,
											   Color.CornflowerBlue, 0, 0);

			// Our player and enemy are both actually just text strings.
			SpriteBatch spriteBatch = ScreenManager.SpriteBatch;

			spriteBatch.Begin(SpriteSortMode.BackToFront, BlendState.AlphaBlend);

			

			//spriteBatch.DrawString(gameFont, "// TODO", playerPosition, Color.Green);

			//spriteBatch.DrawString(gameFont, "Insert Gameplay Here",
			//                       enemyPosition, Color.DarkRed);
			//Draw(Texture2D texture, Vector2 position, Rectangle? sourceRectangle, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth);
			spriteBatch.Draw(testpage, testpagepos, null, Color.White, 0, new Vector2(0, 0), 1, SpriteEffects.None, 1);

			spriteBatch.Draw(playerpanel, playerpanelpos, null, Color.White, 0, new Vector2(0, 0), 1, SpriteEffects.None, 0.99f);

			//virtual thumbstick
			spriteBatch.Draw(controlstick, controlstickpos, null, Color.White, 0, new Vector2(0, 0), 1, SpriteEffects.None, 0.1f);
			spriteBatch.Draw(controlstickBoundary, controlstickBoundarypos, null, Color.White, 0, new Vector2(0, 0), 1, SpriteEffects.None, 0.11f);
			spriteBatch.Draw(jumpbutton, jumpbuttonpos, null, Color.White, 0, new Vector2(0, 0),  1, SpriteEffects.None, 0.95f);
			spriteBatch.Draw(actionbutton, actionbuttonpos, null, Color.White, 0, new Vector2(0, 0), 1, SpriteEffects.None, 0.94f);

			//player
			//spriteBatch.Draw(davinaaktif, davinaaktifpos, null, Color.White, 0, new Vector2(0, 0), new Vector2(0.8f, 0.8f), SpriteEffects.None, 0.96f);
			//spriteBatch.Draw(latifupasif, latifupasifpos, null, Color.White, 0, new Vector2(0, 0), new Vector2(0.8f, 0.8f), SpriteEffects.None, 0.95f);
			spriteBatch.Draw(zakhaevpasif, zakhaevaktifpos, null, Color.White, 0, new Vector2(0, 0), 1, SpriteEffects.None, 0.92f);
			//spriteBatch.Draw(zakhaevpasif, zakhaevpasifpos, null, Color.White, 0, new Vector2(0, 0), new Vector2(0.6f, 0.6f), SpriteEffects.None, 0.94f);
			//spriteBatch.Draw(audriannapasif, audriannaaktifpos, null, Color.White, 0, new Vector2(0, 0), new Vector2(0.6f, 0.6f), SpriteEffects.None, 0.94f);
			spriteBatch.Draw(audriannapasif, audriannapasifpos, null, Color.White, 0, new Vector2(0, 0), 1, SpriteEffects.None, 0.93f);


			spriteBatch.End();

			// If the game is transitioning on or off, fade it out to black.
			if (TransitionPosition > 0)
				ScreenManager.FadeBackBufferToBlack(1f - TransitionAlpha);
		}


		#endregion

		public void Initialize () {
			throw new NotImplementedException();
		}
	}
}
